package com.wzy.runner;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wzy.constant.SystemConstants;
import com.wzy.domain.entity.Article;
import com.wzy.mapper.ArticleMapper;
import com.wzy.mapper.SensitiveWordsMapper;
import com.wzy.service.ArticleCommonService;
import com.wzy.util.RedisCache;
import com.wzy.util.SensitiveWordsUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import static com.wzy.constant.RedisConstants.REDIS_ARTICLE_VIEW_KEY;
import static com.wzy.constant.RedisConstants.SENSITIVE_WORDS_MAP_KEY;
import static com.wzy.constant.SystemConstants.INIT_FROM_DB;
import static com.wzy.constant.SystemConstants.INIT_FROM_TXT;

/**
 * SpringBoot启动执行类
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class RunnerTask implements CommandLineRunner
{
    private final ArticleMapper articleMapper;
    private final RedisCache redisCache;
    private final SensitiveWordsMapper sensitiveWordsMapper;
    private final ArticleCommonService articleCommonService;

    @Value("${spring.sensitive.init-type}")
    private String initType;

    @Value("${spring.sensitive.file-path}")
    private String filePath;

    /**
     * 启动执行任务
     */
    @Override
    public void run(String... args)
    {
        List<Article> articles = articleMapper.selectList(new LambdaQueryWrapper<Article>()
                .eq(Article::getArticleStatus, SystemConstants.RELEASE));
        // 将浏览量存入 redis
        articles.forEach(article ->
                redisCache.setCacheObject(REDIS_ARTICLE_VIEW_KEY + article.getId().toString(),
                        BigInteger.valueOf(article.getViewCount()))
        );
        // 初始化敏感词树存入 redis
        if (Boolean.FALSE.equals(redisCache.hasKey(SENSITIVE_WORDS_MAP_KEY)))
        {
            Map<Object, Object> sensitiveWordsMap = null;
            if (initType.equals(INIT_FROM_TXT))
            {
                sensitiveWordsMap = SensitiveWordsUtils.initSensitiveWordsMapByFile(filePath);
            }
            if (initType.equals(INIT_FROM_DB))
            {
                sensitiveWordsMap = SensitiveWordsUtils.initSensitiveWordsMapByDB(sensitiveWordsMapper.getAllWords());
            }
            redisCache.setCacheObject(SENSITIVE_WORDS_MAP_KEY, sensitiveWordsMap);
        }
        // 初始化文章列表
        articleCommonService.redisArticleList();
    }

}
